package datetype

import (
	"time"
)

type Date time.Time

const (
	FMonth    = "2006-01"
	FDate     = "2006-01-02"
	FDateTime = "2006-01-02 15:04:05"
	OneDay    = time.Hour * 24
)

func (date *Date) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		return nil
	}
	d, err := time.ParseInLocation(`"`+FDate+`"`, string(b), time.Local)
	*date = Date(d)
	return err
}

func (date Date) MarshalJSON() ([]byte, error) {
	t := (time.Time)(date)
	b := make([]byte, 0, len(FDate)+2)
	b = append(b, '"')
	b = t.AppendFormat(b, FDate)
	b = append(b, '"')
	return b, nil
}

type DateTime time.Time

func (date *DateTime) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		return nil
	}
	d, err := time.ParseInLocation(`"`+FDateTime+`"`, string(b), time.Local)
	*date = DateTime(d)
	return err
}

func (date DateTime) MarshalJSON() ([]byte, error) {
	t := (time.Time)(date)
	b := make([]byte, 0, len(FDateTime)+2)
	b = append(b, '"')
	b = t.AppendFormat(b, FDateTime)
	b = append(b, '"')
	return b, nil
}
